package DemoText;
/**
 * 数组中的第 k 个最大的元素
 */

import java.util.Random;

public class LeetCode215 {
    public int findKthLargest(int[] nums, int k) {
        return partition(nums, 0, nums.length - 1, k);
    }
    public int partition(int[] nums, int l, int r, int k) {
        int target = nums[new Random().nextInt(r - l + 1) + l];
        int left = l - 1, right = r + 1,  i = l;
        while (i < right) {
            if (nums[i] > target) swap(nums, --right, i);
            else if (nums[i] == target) i++;
            else swap(nums, ++left, i++);
        }
        //[l, left][left + 1, right - 1][right, r]
        int a = r - right + 1, b = r - left;
        if (k <= a) return partition(nums, right, r, k);
        else if (k <= b) return target;
        else return partition(nums, l, left, k - b);
    }
    public void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
